package utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Base64;

import com.ma.App;
import com.ma.App;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class PictureUtil {

    /**
     * @MethodName: bitmapToString
     * @Description: 把bitmap转换成String
     * @param filePath
     * @return
     */
    public static String bitmapToString(String filePath) {

        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);//30 是压缩率，表示压缩70%; 如果不压缩是100，表示压缩率为0
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    /**
     * @MethodName: readPictureDegree
     * @Description: 计算照片角度
     * @param path 路径
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * @MethodName: rotateBitmap
     * @Description: 旋转图片
     * @param bitmap 图片
     * @param degress 旋转角度
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    /**
     * @MethodName: calculateInSampleSize
     * @Description: 计算图片的缩放值(等比例缩放)
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // heightRatio是图片原始高度与压缩后高度的倍数
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            // widthRatio是图片原始宽度与压缩后宽度的倍数
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // inSampleSize为heightRatio与widthRatio中最小的那个，inSampleSize就是缩放值。 inSampleSize为1表示宽度和高度不缩放，为2表示压缩后的宽度与高度为原来的1/2
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * @MethodName: getSmallBitmap
     * @Description: 根据路径获得图片并缩放,返回bitmap,用于显示
     * @param filePath 路径
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        // 对图片进行解码，inJustDecodeBounds设置为true，可以不把图片读到内存中,但依然可以计算出图片的大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        //获取图片的宽高，这里要设置Options.inJustDecodeBounds=true,这时候decode的bitmap为null,
        //只是把图片的宽高放在Options里，然后第二步就是设置合适的压缩比例inSampleSize，这时候获得合适的Bitmap.
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // 计算缩放值(缩放到480 * 800)
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap bm = BitmapFactory.decodeFile(filePath, options);
        if(bm == null){
            return  null;
        }
        //计算旋转角度
        int degree = readPictureDegree(filePath);
        bm = rotateBitmap(bm,degree) ;
        return bm;
    }

    public static String getIconBitmap(String filePath) {
        return getIconBitmap( filePath,"com_" + System.currentTimeMillis() + ".jpg") ;
    }

    public static String getIconBitmap(String filePath,String fname) {
        // 对图片进行解码，inJustDecodeBounds设置为true，可以不把图片读到内存中,但依然可以计算出图片的大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        //获取图片的宽高，这里要设置Options.inJustDecodeBounds=true,这时候decode的bitmap为null,
        //只是把图片的宽高放在Options里，然后第二步就是设置合适的压缩比例inSampleSize，这时候获得合适的Bitmap.
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // 计算缩放值(缩放到480 * 800)
        options.inSampleSize = calculateInSampleSize(options, 50, 50);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap bm = BitmapFactory.decodeFile(filePath, options);
        if(bm == null){
            return  null;
        }
        //计算旋转角度
        int degree = readPictureDegree(filePath);
        bm = rotateBitmap(bm,degree) ;
        FileOutputStream out = null;
        File outputFile = null;
        try {
            outputFile = new File(getCompressDir(),fname);
            out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, 50, out);//40 是压缩率，表示压缩60%; 如果不压缩是100，表示压缩率为0
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally{
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outputFile.getAbsolutePath() ;
    }

    /**
     * @MethodName: getSmallBitmap
     * @Description: 压缩图片,并保存在一个临时路径
     * @param filePath
     * @return
     */
    @SuppressLint("NewApi")
    public static String getCompressBitmap(String filePath) {
        return getCompressBitmap( filePath,"com_" + System.currentTimeMillis() + ".jpg") ;
    }
      static String getCompressBitmap(String filePath,String fileName) {
        File getSize = new File(filePath);
        int picLength = (int) (getSize.length() / 1024);
        //计算图片大小,对于大于300KB的进行压缩
        if(picLength > 300){
            final BitmapFactory.Options options = new BitmapFactory.Options();
            //option.inJustDecodeBounds = true;表示仅读取图片文件信息而不为图片分配内存。
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, 480, 800);

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;

            Bitmap bm = BitmapFactory.decodeFile(filePath, options);
            if(bm == null){
                return  filePath;
            }
            //计算旋转角度
            int degree = readPictureDegree(filePath);
            bm = rotateBitmap(bm,degree) ;

            FileOutputStream out = null;
            File outputFile = null;
            try {
                outputFile = new File(getCompressDir(),fileName);
                out = new FileOutputStream(outputFile);
                bm.compress(Bitmap.CompressFormat.JPEG, 50, out);//40 是压缩率，表示压缩60%; 如果不压缩是100，表示压缩率为0
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } finally{
                try {
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return outputFile.getAbsolutePath() ;
        } else {
            return filePath;
        }

    }

    /**
     * 获取保存压缩图片的目录
     *
     * @return
     */
      static File getCompressDir() {
        String path = App.getInstance().getCacheDir().getPath();
        File file = new File(path);
        // 检测路径是否存在
        if (!file.exists()) {
            file.mkdirs();//创建该路径
        }
        return file;
    }



    //递归删除文件及文件夹
    public static void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

        if(file.isDirectory()){
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }



    /**
     * @MethodName: getDate
     * @Description: 得到当前时间
     * @return 时间的字符串
     */
    public static String getDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timeStamp = format.format(new Date());
        return timeStamp;
    }
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "") ;
    }
}
